import datetime
import time
from time import strftime

from flask import Blueprint, render_template, request

from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db

from applications.models import Score,PoliceModels,Scene
from applications.schemas import ScoreOutSchema

admin_trainscore = Blueprint('adminScore', __name__, url_prefix='/admin/score')


# 心理诱导互动训练评估
@admin_trainscore.get('/')
def main():
    return render_template('admin/train/train_score.html')

# @admin_trainscore.get('/details')
# def details_info():
#     return render_template('admin/train/details.html')

#   用户分页查询
@admin_trainscore.get('/data')
def data():
    # 获取请求参数
    scenename = xss_escape(request.args.get('scene_name', type=str))
    trainname = xss_escape(request.args.get('train_name', type=str))
    username = xss_escape(request.args.get('user_name', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if scenename:
        mf.contains(field_name="scene_name", value=scenename)
    if trainname:
        mf.contains(field_name="train_name", value=trainname)
    if username:
        mf.contains(field_name="user_name", value=username)

    # mf.inlist(field_name="id", value=l)

    # orm查询
    # 使用分页获取data需要.items
    train = Score.query.filter(mf.get_filter(model=Score)).layui_paginate()
    count = train.total
    # 返回api
    return table_api(data=model_to_dicts(schema=ScoreOutSchema, data=train.items), count=count)


@admin_trainscore.get('/idList/<string:idList>')
def getId(idList):
    Score.query.delete()
    global l,l1,l2
    l = []
    l1 = []
    l2 = []
    j = 0
    time_now=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    for i in idList.split(','):
        if i.isdigit():
            j += 1
            if j%2 == 0:
                l2.append(i)
            else:
                l1.append(i)
            if len(l1) == len(l2):
                police = PoliceModels.query.filter_by(code=l1[len(l1)-1]).first()
                scene = Scene.query.filter_by(id=l2[len(l2)-1]).first()

                record = Score(id=len(l1),user_id=police.code,type_id=scene.id,scene_name=scene.content,train_name=scene.version,\
                                     user_name=police.name,enable=1,train_data=None,start_time=time_now,end_time=None)
                db.session.add(record)

    db.session.commit()
    return render_template('admin/train/train_score.html')